package com.tchintech.pay.view.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tchintech.pay.R;
import com.tchintech.pay.delegate.RegisterActivityDelegate;
import com.tchintech.pay.frame.presenter.ActivityPresenter;
import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.net.OkhttpClientTest;
import com.tchintech.pay.utils.RegexUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.sms.SMSSDK;
import cn.jpush.sms.listener.SmscheckListener;
import cn.jpush.sms.listener.SmscodeListener;

/**
 * Created by Administrator on 2017/7/6 0006.
 */

public class RegisterActivity extends ActivityPresenter<RegisterActivityDelegate> implements View.OnClickListener {
    private final String url_Register = "Register.register";
    protected HashMap<String, String> map;
    private Handler handler;
    private String authId = "";
    private TextView tv_code;
    private RelativeLayout Register_rel;
    //用户名，电话号码，密码，重复密码，验证码,推荐人；
    private String phoneNumber, password, str_code, recommend;
    private TimerTask timerTask;
    private int timess;
    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        super.initView();
        viewDelegate.setTitle("用户注册");
        viewDelegate.setVisible();
        tv_code = viewDelegate.getTextView(R.id.register_bt_send_verify_code);
        Register_rel = viewDelegate.getRegister_rel();
        viewDelegate.setOnClickListener(this, R.id.register_bt_register, R.id.register_rel, R.id.iv_back);
        handler();
    }

    private void handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                hideProgressDialog();
                switch (msg.what) {
                    case HttpCode.networkabnormal:
                        showMsg("当前网络不可用");
                        break;
                    case HttpCode.http_failed:
                        showMsg("连接失败");
                        break;
                    case HttpCode.http_timeout:
                        showMsg("请求超时");
                        break;
                    case HttpCode.register:
                        try {
                          //  showMsg(json.getString("msg"));
                            JSONObject json = new JSONObject(msg.obj.toString());
                            if (json.getString("ret").equals("1")) {
                                getSpUtils().write("phoneNumber", phoneNumber);
                                showMsg("注册成功");
                                setResult(RESULT_OK);
                                finish();
                            } else {
                                showMsg(json.getString("msg"));
                            }
                        } catch (Exception e) {
                            System.out.println("okhttp转换失败" + e);
                            e.printStackTrace();
                        }
                        break;


                }
            }
        };
    }

    @Override
    protected Class<RegisterActivityDelegate> getDelegateClass() {
        return RegisterActivityDelegate.class;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_rel:
                //获取验证码
                judge(1);
                break;
            case R.id.register_bt_register:
                //注册按钮
                judge(2);
                break;
            case R.id.iv_back:
                finish();
                break;
        }

    }

    //获取短信验证码
    private void getCode() {

        SMSSDK.getInstance().getSmsCodeAsyn(phoneNumber, "137715", new SmscodeListener() {
            @Override
            public void getCodeSuccess(final String uuid) {
                showMsg("短信发送成功");
                startTimer();
            }

            @Override
            public void getCodeFail(int errCode, final String errmsg) {
                //失败后停止计时
                showMsg("短信发送失败");
                System.out.println("错误代码是：" + errmsg);
            }
        });
    }

    //验证验证码
    private void checkCode(String str_code) {
        showProgressDialog("", "加载中，请稍后...");
        SMSSDK.getInstance().checkSmsCodeAsyn(phoneNumber, str_code, new SmscheckListener() {
            @Override
            public void checkCodeSuccess(final String code) {
                //成功 执行下一步操作
                hideProgressDialog();
                registerSubmit();
            }

            @Override
            public void checkCodeFail(int errCode, final String errmsg) {
                hideProgressDialog();
                //失败
                showMsg("验证码输入有误请重新输入");
            }
        });
    }

    //注册数据组装
    private void registerSubmit() {
        map = new HashMap<String, String>();
        map.put("username", phoneNumber);
        map.put("password", password);
        map.put("phone", phoneNumber);
        map.put("father", recommend);
        showProgressDialog("", "加载中，请稍后...");
        new OkhttpClientTest().path(this, handler, url_Register, map, HttpCode.register);
    }

    /**
     * 判断
     * type  1:发送验证码  2：注册
     */
    private void judge(int type) {
        phoneNumber = viewDelegate.getEditString(R.id.register_ed_phoneNumber);
        password = viewDelegate.getEditString(R.id.register_ed_password);
        recommend = viewDelegate.getEditString(R.id.register_ed_recommend);
        if (RegexUtils.checkPhoneNumber(phoneNumber) && !"".equals(phoneNumber)) {
            if (!password.equals("")) {
                //执行操作
                if (type == 1) {
                    getCode();
                } else {
                    str_code = viewDelegate.getEditString(R.id.register_ed_verify_code);
                    if (str_code.equals("")) {
                        showMsg("请输入验证码");
                    } else {
                        checkCode(str_code);
                    }
                }
            } else {
                showMsg("密码不能为空");
                return;
            }
        } else {
            showMsg("请输入正确的手机号码");
            return;
        }
    }

    private void startTimer() {
        Register_rel.setClickable(false);
        timess = (int) (SMSSDK.getInstance().getIntervalTime() / 1000);
        tv_code.setText(timess + "秒后获取");
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            timess--;
                            if (timess <= 0) {
                                stopTimer();
                                return;
                            }
                            tv_code.setText(timess + "秒后获取");
                        }
                    });
                }
            };
        }
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(timerTask, 1000, 1000);
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        tv_code.setText("发送验证码");
        Register_rel.setClickable(true);
    }
}
